//
//  URLParamUtil.m
//  qw-troad-ios
//
//  Created by Yunhai.Wu on 15/8/13.
//  Copyright (c) 2015年 117go. All rights reserved.
//

#import "QWURLUtils.h"
#import "QWStringUtils.h"

@implementation QWURLUtils

+ (NSDictionary *) paramsWithFormURL:(NSString *) URL {
    if (!URL) {
        return nil;
    }
    NSArray *c1 = [URL componentsSeparatedByString:@"?"];
    NSString *paramsString = nil;
    if ([c1 count] == 2) {
        paramsString = c1[1];
    }
    if (paramsString) {
        NSMutableDictionary *result = [NSMutableDictionary dictionary];
        NSArray *pairs = [paramsString componentsSeparatedByString:@"&"];
        for (NSString *kvp in pairs) {
            if ([kvp length] == 0) {
                continue;
            }
            
            NSRange pos = [kvp rangeOfString:@"="];
            NSString *key;
            NSString *val;
            
            if (pos.location == NSNotFound) {
                key = [self stringByUnescapingFromURLQuery:kvp];
                val = @"";
            } else {
                key = [self stringByUnescapingFromURLQuery:[kvp substringToIndex:pos.location]];
                val = [self stringByUnescapingFromURLQuery:[kvp substringFromIndex:pos.location + pos.length]];
            }
            if (!key || !val) {
                continue;
            }
            
            [result setObject:val forKey:key];
        }
        return result;
    }
    return nil;
}

+ (NSString *) stringByUnescapingFromURLQuery:(NSString*) str {
    NSString *deplussed = [str stringByReplacingOccurrencesOfString:@"+" withString:@" "];
    return [deplussed stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
}

+ (NSString *) stringWithFormParams:(NSDictionary*) params {
    if ([params count] > 0) {
        NSMutableArray *arguments = [NSMutableArray arrayWithCapacity:[params count]];
        [params enumerateKeysAndObjectsUsingBlock:^(id key, id object, BOOL *stop) {
            [arguments addObject:[NSString stringWithFormat:@"%@=%@",
                                  [self stringByEscapingForURLQuery:key],
                                  [self stringByEscapingForURLQuery:[object description]]]];
        }];
        return [arguments componentsJoinedByString:@"&"];
    }
    return nil;
}

+ (NSString *)stringByEscapingForURLQuery:(NSString*) key {
    NSString *result = key;
    static CFStringRef leaveAlone = CFSTR(" ");
    static CFStringRef toEscape = CFSTR("\n\r:/=,!$&'()*+;[]@#?%");
    CFStringRef escapedStr = CFURLCreateStringByAddingPercentEscapes(kCFAllocatorDefault, (__bridge CFStringRef)key, leaveAlone,
                                                                     toEscape, kCFStringEncodingUTF8);
    if (escapedStr) {
        NSMutableString *mutable = [NSMutableString stringWithString:(__bridge NSString *)escapedStr];
        CFRelease(escapedStr);
        [mutable replaceOccurrencesOfString:@" " withString:@"+" options:NSCaseInsensitiveSearch range:NSMakeRange(0, [mutable length])];
        result = mutable;
    }
    return result;
}


+(NSString *)removeURLParams:(NSString *)URL {
    if ([QWStringUtils isNotBlank:URL]) {
        return [URL componentsSeparatedByString:@"?"][0];
    }
    return nil;
}

@end
